package com.neu.envprotection.feedback.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.neu.envprotection.admin.dao.entity.User;

import com.neu.envprotection.admin.feign.UserFeign;

import com.neu.envprotection.common.resp.PageRespDto;
import com.neu.envprotection.common.resp.RestResp;
import com.neu.envprotection.feedback.dao.entity.*;
import com.neu.envprotection.feedback.dao.mapper.*;
import com.neu.envprotection.feedback.dto.req.*;
import com.neu.envprotection.feedback.dto.resp.FeedbackRespDto;
import com.neu.envprotection.feedback.dto.resp.ReportChinaChartsRespDto;
import com.neu.envprotection.feedback.dto.resp.SupervisorPersonalInfoRespDto;
import com.neu.envprotection.feedback.service.SupervisorService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 监督员业务模块
 */

@Service
@RequiredArgsConstructor
@Slf4j
@Transactional
public class SupervisorServiceImpl implements SupervisorService {
    private final ProvienceMapper provienceMapper;
    private final CityMapper cityMapper;
    private final EnvGridMapper envGridMapper;
    private final FeedbackMapper feedbackMapper;
    private final RankMapper rankMapper;

    private final UserFeign userFeign;
//    private final UserMapper userMapper;

    //向监督员展示所有可选省
    @Override
    public RestResp<List<Provience>> showAllProvince() {
        return RestResp.ok(provienceMapper.selectList(null));
    }

    //根据监督员选择的省展示所有可选市
    @Override
    public RestResp<List<City>> showCitiesRingP(Integer provinceId) {
        QueryWrapper<City> cityQueryWrapper = new QueryWrapper<>();
        cityQueryWrapper.eq("provience_id",provinceId);
        return RestResp.ok(cityMapper.selectList(cityQueryWrapper));
    }

    //监督者填写具体地址
    @Override
    public RestResp<Void> insertSpecificGrid(SupervisorSpecificGridReqDto supervisorSpecificGridReqDto) {
        EnvGrid envGrid = new EnvGrid();
        envGrid.setProvienceId(supervisorSpecificGridReqDto.getProvinceId());
        envGrid.setCityId(supervisorSpecificGridReqDto.getCityId());
        envGrid.setAddress(supervisorSpecificGridReqDto.getAddress());
        envGrid.setUserId(supervisorSpecificGridReqDto.getUserId());
        envGrid.setCreateTime(LocalDateTime.now());
        envGridMapper.insert(envGrid);
        return null;
    }

    //向监督员展示所有分级
    @Override
    public RestResp<List<Rank>> showAllRanks() {
        return RestResp.ok(rankMapper.selectRanks());
    }


    //监督者查看所有历史反馈信息
//    @Override
//    public RestResp<List<ViewJudgeRespDto>> viewFeedback(Integer userId) {
//        //用于将grid数据转化为省市数据
//       // ViewJudgeRespDto viewJudgeRespDto = ViewJudgeRespDto.builder().build();
//        Integer gridId = 0;
//        String province = null;
//        String city = null;
//
//
//        QueryWrapper<Feedback> feedbackQueryWrapper = new QueryWrapper<>();
//        feedbackQueryWrapper.eq("user_id",userId);
//        List<Feedback> feedbackList = feedbackMapper.selectList(feedbackQueryWrapper);
//        List<ViewJudgeRespDto> viewJudgeRespDtoList = new ArrayList<>();
//        for(Feedback feedback:feedbackList){
//            gridId = feedback.getGridId();
//            province = provienceMapper.selectById(envGridMapper.selectById(gridId).getProvienceId()).getProvienceName();
//            city = cityMapper.selectById(envGridMapper.selectById(gridId).getCityId()).getCity();
////            viewJudgeRespDto.setCity(city);
////            viewJudgeRespDto.setFeedback(feedback.getFeedback());
////            viewJudgeRespDto.setRank(feedback.getRankId());
////            viewJudgeRespDto.setProvince(province);
////            viewJudgeRespDto.setLocalDateTime(feedback.getCreateTime());
//            //viewJudgeRespDtoList.add(viewJudgeRespDto);
//        }
//        return RestResp.ok(viewJudgeRespDtoList);
//    }

    //监督者添加反馈信息
    @Override
    public RestResp<Void> insertFeedback(SupervisorFeedbackAddReqDto supervisorFeedbackAddReqDto) {
        //存储监督者新建的网格信息
        EnvGrid envGrid = new EnvGrid();
        //存储监督者新建的反馈信息
        Feedback feedback = new Feedback();
        //整理网格信息
        envGrid.setUserId(supervisorFeedbackAddReqDto.getSId());
        envGrid.setProvienceId(supervisorFeedbackAddReqDto.getPId());
        envGrid.setCityId(supervisorFeedbackAddReqDto.getCId());
        envGrid.setAddress(supervisorFeedbackAddReqDto.getAddress());
        envGrid.setCreateTime(LocalDateTime.parse(supervisorFeedbackAddReqDto.getFDateTime()));
        envGridMapper.insert(envGrid);
        //整理反馈信息
        feedback.setUserId(supervisorFeedbackAddReqDto.getSId());
        feedback.setFeedback(supervisorFeedbackAddReqDto.getInfo());
        feedback.setGridId(envGrid.getId());
        feedback.setIsDelete(1);
        feedback.setIsAssigned(0);
        feedback.setRankId(Integer.parseInt(supervisorFeedbackAddReqDto.getEstimatedGrade()));
        feedback.setUserId(supervisorFeedbackAddReqDto.getSId());
        feedback.setCreateTime(LocalDateTime.parse(supervisorFeedbackAddReqDto.getFDateTime()));
        feedbackMapper.insert(feedback);
        return null;
    }

    //监督者查询反馈记录
    @Override
    public RestResp<PageRespDto<FeedbackRespDto>> viewFeedback(SupervisorFeedbackViewReqDto supervisorFeedbackViewReqDto) {
        //ViewJudgeRespDto viewJudgeRespDto = ViewJudgeRespDto.builder().build();
        //viewJudgeRespDto.setFeedbackList(new ArrayList<FeedbackRespDto>());
        Page<Feedback> page = new Page<>(supervisorFeedbackViewReqDto.getPageNum(),supervisorFeedbackViewReqDto.getPageSize());
        QueryWrapper<Feedback> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",supervisorFeedbackViewReqDto.getSId());
        IPage<Feedback> feedbackPage = feedbackMapper.selectPage(page, queryWrapper);


        EnvGrid envGrid = new EnvGrid();
        Provience provience = new Provience();
        City city = new City();
        User user = new User();
        String provinceName = null;
        String cityName = null;
        String userName = null;
        List<FeedbackRespDto> list = new ArrayList<FeedbackRespDto>();

        for(Feedback feedback: page.getRecords()){
            //将feedback原始数据处理成用户数据
            FeedbackRespDto feedbackRespDto = FeedbackRespDto.builder().build();
            feedbackRespDto.setId(feedback.getId());
            feedbackRespDto.setFeedback(feedback.getFeedback());
            feedbackRespDto.setGridId(feedback.getGridId());
            //获得表格信息
            envGrid = envGridMapper.selectById(feedback.getGridId());
            System.out.println("分页id："+feedback.getId());
            //System.out.println("表格城市id是："+envGrid.getCityId());
            //获取省信息
            provience = provienceMapper.selectById(envGrid.getProvienceId());
            provinceName = provience.getProvienceName();
            feedbackRespDto.setProvinceName(provinceName);
            //获取市信息
            city = cityMapper.selectById(envGrid.getCityId());
            cityName = city.getCity();
            feedbackRespDto.setCityName(cityName);

            feedbackRespDto.setIsDelete(feedback.getIsDelete());
            feedbackRespDto.setRankId(feedback.getRankId());
            feedbackRespDto.setIsAssigned(feedback.getIsAssigned());

            //获取填写者信息
            user = userFeign.selectById(feedback.getUserId()).getData();
            userName = user.getName();
            feedbackRespDto.setUserName(userName);

            feedbackRespDto.setCreateTime(feedback.getCreateTime().toLocalDate());

            list.add(feedbackRespDto);
            for(FeedbackRespDto feedbackRespDto1:list){
                System.out.println("分页循环："+feedbackRespDto1.getId());
            }
            System.out.println("-----------------------------------");

        }

        //测试
        for(FeedbackRespDto feedbackRespDto1:list){
            System.out.println("分页信息："+feedbackRespDto1.getId());
        }
        System.out.println("-----------------------------------");
        PageRespDto<FeedbackRespDto> res = PageRespDto.of(supervisorFeedbackViewReqDto.getPageNum(),supervisorFeedbackViewReqDto.getPageSize(),page.getTotal(),list);
        return RestResp.ok(res);
    }

    //监督者查看个人信息，其中phoneNumber/birthday/sex未知，需传回
    @Override
    public RestResp<SupervisorPersonalInfoRespDto> getPersonalInfo(Integer userId) {
        System.out.println("userId:"+userId);
        User user = new User();
        user = userFeign.selectById(userId).getData();
        return RestResp.ok(SupervisorPersonalInfoRespDto.builder().sex(user.getSex()).phoneNumber(user.getPhoneNumber()).birthday(user.getBirthDay().toLocalDate()).build());
    }

    @Override
    public RestResp<Void> updateInfo(SupervisorUpdateReqDto supervisorUpdateReqDto) {
        User user = new User();
        user.setId(supervisorUpdateReqDto.getId());
        user.setSex(supervisorUpdateReqDto.getSex());
        user.setName(supervisorUpdateReqDto.getUserName());
        user.setBirthDay(supervisorUpdateReqDto.getBirthday().atStartOfDay());
        user.setPhoneNumber(supervisorUpdateReqDto.getPhoneNumber());
        System.out.println("updateId:"+user.getId());
        userFeign.updateById(user);
        return RestResp.ok();
    }

    @Override
    public RestResp<Void> updatePassword(SupervisorUpdatePwdReqDto supervisorUpdatePwdReqDto) {
        User user = new User();
        user.setId(supervisorUpdatePwdReqDto.getId());
        user.setPassword(DigestUtils.md5DigestAsHex(supervisorUpdatePwdReqDto.getPassword().getBytes(StandardCharsets.UTF_8)));
        userFeign.updateById(user);
        return RestResp.ok();
    }

    @Override
    public RestResp<List<ReportChinaChartsRespDto>> getProvinceAQI() {
        return RestResp.ok(feedbackMapper.getProvinceAQI());
    }

}
